import unittest

from django.contrib.auth.models         import User,Group,Permission
from django.contrib.sites.models        import Site
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions             import ValidationError
from sitepal.sitebase.models            import Access,Property,Tree
from sitepal.sitebase.tests.models.base import BaseTest

class AccessTest(BaseTest):
    def setUp(self):
        self.user  = User.objects.create_superuser('admin','admin@localhost.local','admin')
        self.group = Group.objects.create(name='authenticated')
        self.perm  = Permission.objects.get_by_natural_key('add_property','sitebase','property')
        self.prop  = Property.objects.create(name='test-property',value='test value',usage='staff',
                                             creator=self.user,owner=self.user)
        self.site  = Site.objects.get_current()

    def create_object(self,obj,save=True,**kwargs):
        self.assertTrue(isinstance(obj,Access))
        obj.user       = kwargs.get('user')
        obj.group      = kwargs.get('group')
        obj.permission = kwargs['permission']
        obj.grantee    = kwargs['grantee']
        obj.granter    = kwargs.get('granter',self.user)
        if 'inherits' in kwargs:
            obj.inherits = kwargs['inherits']
        if 'site' in kwargs:
            obj.site = kwargs['site']
        return self.save_object(obj,save=save)

    def verify_object(self,obj,**kwargs):
        self.assertTrue(isinstance(obj,Access))
        self.assertTrue (obj.user == kwargs.get('user'))
        self.assertTrue (obj.group == kwargs.get('group'))
        self.assertTrue(obj.permission   == kwargs['permission'])
        self.assertTrue(obj.inherits     == kwargs.get('inherits',False))
        self.assertTrue(obj.grantee      == kwargs['grantee'])
        self.assertTrue(obj.grantee_type == ContentType.objects.get_for_model(kwargs['grantee']))
        self.assertTrue(obj.grantee_id   == kwargs['grantee'].pk)
        self.assertTrue(obj.site         == kwargs.get('site',self.site))
        self.assertTrue(obj.granter      == kwargs.get('granter',self.user))
        self.assertTrue(obj.date_granted)
        if obj.inherits:
            self.assertTrue(isinstance(obj.grantee,Tree))

    def create_access(self,**kwargs):
        obj = self.create_object(Access(),save=True,**kwargs)
        self.verify_object(obj,**kwargs)
        return obj

    def testCreate(self):
        a1 = self.create_access(user=self.user,permission=self.perm,grantee=self.prop)
        a2 = self.create_access(group=self.group,permission=self.perm,grantee=self.prop)
        self.assertRaises(ValidationError,self.create_access,user=self.user,group=self.group,permission=self.perm,grantee=self.prop)
        self.assertRaises(ValidationError,self.create_access,permission=self.perm,grantee=self.prop)

def suite():
    return unittest.TestLoader().loadTestsFromTestCase(AccessTest)
